#!/usr/bin/env python
"""
百家乐系统数据库模型类
定义与数据库表对应的类结构
"""
import os
import json
import time
import psycopg2
from psycopg2.extras import RealDictCursor
from config import DB_CONFIG

def get_db_connection():
    """获取数据库连接"""
    try:
        conn = psycopg2.connect(**DB_CONFIG)
        return conn
    except Exception as e:
        print(f"数据库连接错误: {str(e)}")
        return None

def get_timestamp():
    """获取当前时间戳"""
    return time.strftime('%Y-%m-%d %H:%M:%S')

class Round:
    """游戏轮次模型类，对应rounds表"""
    
    def __init__(self, id=None, timestamp=None, bet_choice="", bet_amount=0, 
                result="", win_or_lose=0, payout=0, player_hand=None, 
                banker_hand=None, player_points=0, banker_points=0, main_choice=None):
        """初始化游戏轮次对象"""
        self.id = id
        self.timestamp = timestamp or get_timestamp()
        self.bet_choice = bet_choice
        self.bet_amount = bet_amount
        self.result = result
        self.win_or_lose = win_or_lose
        self.payout = payout
        self.player_hand = player_hand or []
        self.banker_hand = banker_hand or []
        self.player_points = player_points
        self.banker_points = banker_points
        self.main_choice = main_choice
    
    @staticmethod
    def from_dict(data):
        """从字典创建对象"""
        instance = Round()
        for key, value in data.items():
            if key in ['player_hand', 'banker_hand'] and isinstance(value, str):
                setattr(instance, key, json.loads(value))
            else:
                setattr(instance, key, value)
        return instance
    
    def to_dict(self):
        """将对象转换为字典"""
        result = {
            'id': self.id,
            'timestamp': self.timestamp,
            'bet_choice': self.bet_choice,
            'bet_amount': self.bet_amount,
            'result': self.result,
            'win_or_lose': self.win_or_lose,
            'payout': self.payout,
            'player_hand': self.player_hand,
            'banker_hand': self.banker_hand,
            'player_points': self.player_points,
            'banker_points': self.banker_points,
            'main_choice': self.main_choice
        }
        return result
    
    def save(self):
        """保存到数据库"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            cursor = conn.cursor()
            
            # 准备JSON字段
            player_hand_json = json.dumps(self.player_hand)
            banker_hand_json = json.dumps(self.banker_hand)
            
            if self.id:  # 更新
                cursor.execute('''
                    UPDATE rounds SET
                    timestamp = %s, bet_choice = %s, bet_amount = %s, 
                    result = %s, win_or_lose = %s, payout = %s,
                    player_hand = %s, banker_hand = %s, 
                    player_points = %s, banker_points = %s, main_choice = %s
                    WHERE id = %s
                    RETURNING id
                ''', (
                    self.timestamp, self.bet_choice, self.bet_amount,
                    self.result, self.win_or_lose, self.payout,
                    player_hand_json, banker_hand_json,
                    self.player_points, self.banker_points, self.main_choice,
                    self.id
                ))
            else:  # 插入
                cursor.execute('''
                    INSERT INTO rounds (
                        timestamp, bet_choice, bet_amount, result, win_or_lose, payout,
                        player_hand, banker_hand, player_points, banker_points, main_choice
                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                    RETURNING id
                ''', (
                    self.timestamp, self.bet_choice, self.bet_amount,
                    self.result, self.win_or_lose, self.payout,
                    player_hand_json, banker_hand_json,
                    self.player_points, self.banker_points, self.main_choice
                ))
            
            # 获取ID
            result = cursor.fetchone()
            if result:
                self.id = result[0]
            
            conn.commit()
            return True
        
        except Exception as e:
            print(f"保存轮次错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def get_by_id(round_id):
        """根据ID获取对象"""
        conn = get_db_connection()
        if not conn:
            return None
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM rounds WHERE id = %s', (round_id,))
            data = cursor.fetchone()
            
            if not data:
                return None
            
            return Round.from_dict(data)
        
        except Exception as e:
            print(f"获取轮次错误: {str(e)}")
            return None
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def get_all(limit=10):
        """获取多个对象"""
        conn = get_db_connection()
        if not conn:
            return []
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM rounds ORDER BY id DESC LIMIT %s', (limit,))
            data = cursor.fetchall()
            
            return [Round.from_dict(row) for row in data]
        
        except Exception as e:
            print(f"获取轮次列表错误: {str(e)}")
            return []
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def delete(round_id):
        """删除对象"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            cursor = conn.cursor()
            cursor.execute('DELETE FROM rounds WHERE id = %s', (round_id,))
            conn.commit()
            return True
        
        except Exception as e:
            print(f"删除轮次错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def clear_all():
        """清空所有记录"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            cursor = conn.cursor()
            cursor.execute('TRUNCATE TABLE rounds RESTART IDENTITY')
            conn.commit()
            return True
        
        except Exception as e:
            print(f"清空轮次错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            conn.close()


class Simulation:
    """模拟记录模型类，对应simulations表"""
    
    def __init__(self, id=None, timestamp=None, strategy_name="", total_rounds=0,
                win_rounds=0, lose_rounds=0, net_profit=0.0, deck_seed=None, 
                parameters=None, main_choice=None):
        """初始化模拟记录对象"""
        self.id = id
        self.timestamp = timestamp or get_timestamp()
        self.strategy_name = strategy_name
        self.total_rounds = total_rounds
        self.win_rounds = win_rounds
        self.lose_rounds = lose_rounds
        self.net_profit = net_profit
        self.deck_seed = deck_seed
        self.parameters = parameters or {}
        self.main_choice = main_choice
    
    @staticmethod
    def from_dict(data):
        """从字典创建对象"""
        instance = Simulation()
        for key, value in data.items():
            if key == 'parameters' and isinstance(value, str):
                try:
                    setattr(instance, key, json.loads(value))
                except:
                    setattr(instance, key, {})
            else:
                setattr(instance, key, value)
        return instance
    
    def to_dict(self):
        """将对象转换为字典"""
        result = {
            'id': self.id,
            'timestamp': self.timestamp,
            'strategy_name': self.strategy_name,
            'total_rounds': self.total_rounds,
            'win_rounds': self.win_rounds,
            'lose_rounds': self.lose_rounds,
            'net_profit': self.net_profit,
            'deck_seed': self.deck_seed,
            'parameters': self.parameters,
            'main_choice': self.main_choice
        }
        return result
    
    def save(self):
        """保存到数据库"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            cursor = conn.cursor()
            
            # 参数转JSON
            parameters_json = json.dumps(self.parameters) if self.parameters else '{}'
            
            if self.id:  # 更新
                cursor.execute('''
                    UPDATE simulations SET
                    timestamp = %s, strategy_name = %s, total_rounds = %s,
                    win_rounds = %s, lose_rounds = %s, net_profit = %s,
                    deck_seed = %s, parameters = %s, main_choice = %s
                    WHERE id = %s
                    RETURNING id
                ''', (
                    self.timestamp, self.strategy_name, self.total_rounds,
                    self.win_rounds, self.lose_rounds, self.net_profit,
                    self.deck_seed, parameters_json, self.main_choice,
                    self.id
                ))
            else:  # 插入
                cursor.execute('''
                    INSERT INTO simulations (
                        timestamp, strategy_name, total_rounds, win_rounds, 
                        lose_rounds, net_profit, deck_seed, parameters, main_choice
                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
                    RETURNING id
                ''', (
                    self.timestamp, self.strategy_name, self.total_rounds,
                    self.win_rounds, self.lose_rounds, self.net_profit,
                    self.deck_seed, parameters_json, self.main_choice
                ))
            
            # 获取ID
            result = cursor.fetchone()
            if result:
                self.id = result[0]
            
            conn.commit()
            return True
        
        except Exception as e:
            print(f"保存模拟记录错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def get_by_id(sim_id):
        """根据ID获取对象"""
        conn = get_db_connection()
        if not conn:
            return None
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM simulations WHERE id = %s', (sim_id,))
            data = cursor.fetchone()
            
            if not data:
                return None
            
            return Simulation.from_dict(data)
        
        except Exception as e:
            print(f"获取模拟记录错误: {str(e)}")
            return None
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def get_all(limit=10):
        """获取多个对象"""
        conn = get_db_connection()
        if not conn:
            return []
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM simulations ORDER BY id DESC LIMIT %s', (limit,))
            data = cursor.fetchall()
            
            return [Simulation.from_dict(row) for row in data]
        
        except Exception as e:
            print(f"获取模拟记录列表错误: {str(e)}")
            return []
        
        finally:
            if cursor:
                cursor.close()
            conn.close()


class SimulationRound:
    """模拟轮次模型类，对应simulation_rounds表"""
    
    def __init__(self, id=None, timestamp=None, simulation_id=None, round_id=0,
                bet_choice="", bet_amount=0, result="", win_or_lose=0, payout=0, 
                player_hand=None, banker_hand=None, player_points=0, 
                banker_points=0, strategy_note="", main_choice=None):
        """初始化模拟轮次对象"""
        self.id = id
        self.timestamp = timestamp or get_timestamp()
        self.simulation_id = simulation_id
        self.round_id = round_id
        self.bet_choice = bet_choice
        self.bet_amount = bet_amount
        self.result = result
        self.win_or_lose = win_or_lose
        self.payout = payout
        self.player_hand = player_hand or []
        self.banker_hand = banker_hand or []
        self.player_points = player_points
        self.banker_points = banker_points
        self.strategy_note = strategy_note
        self.main_choice = main_choice
    
    @staticmethod
    def from_dict(data):
        """从字典创建对象"""
        instance = SimulationRound()
        for key, value in data.items():
            if key in ['player_hand', 'banker_hand'] and isinstance(value, str):
                setattr(instance, key, json.loads(value))
            else:
                setattr(instance, key, value)
        return instance
    
    def to_dict(self):
        """将对象转换为字典"""
        result = {
            'id': self.id,
            'timestamp': self.timestamp,
            'simulation_id': self.simulation_id,
            'round_id': self.round_id,
            'bet_choice': self.bet_choice,
            'bet_amount': self.bet_amount,
            'result': self.result,
            'win_or_lose': self.win_or_lose,
            'payout': self.payout,
            'player_hand': self.player_hand,
            'banker_hand': self.banker_hand,
            'player_points': self.player_points,
            'banker_points': self.banker_points,
            'strategy_note': self.strategy_note,
            'main_choice': self.main_choice
        }
        return result
    
    def save(self):
        """保存到数据库"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            cursor = conn.cursor()
            
            # 准备JSON字段
            player_hand_json = json.dumps(self.player_hand)
            banker_hand_json = json.dumps(self.banker_hand)
            
            if self.id:  # 更新
                cursor.execute('''
                    UPDATE simulation_rounds SET
                    timestamp = %s, simulation_id = %s, round_id = %s,
                    bet_choice = %s, bet_amount = %s, result = %s, 
                    win_or_lose = %s, payout = %s, player_hand = %s, 
                    banker_hand = %s, player_points = %s, banker_points = %s,
                    strategy_note = %s, main_choice = %s
                    WHERE id = %s
                    RETURNING id
                ''', (
                    self.timestamp, self.simulation_id, self.round_id,
                    self.bet_choice, self.bet_amount, self.result,
                    self.win_or_lose, self.payout, player_hand_json,
                    banker_hand_json, self.player_points, self.banker_points,
                    self.strategy_note, self.main_choice, self.id
                ))
            else:  # 插入
                cursor.execute('''
                    INSERT INTO simulation_rounds (
                        timestamp, simulation_id, round_id, bet_choice, bet_amount,
                        result, win_or_lose, payout, player_hand, banker_hand,
                        player_points, banker_points, strategy_note, main_choice
                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                    RETURNING id
                ''', (
                    self.timestamp, self.simulation_id, self.round_id,
                    self.bet_choice, self.bet_amount, self.result,
                    self.win_or_lose, self.payout, player_hand_json,
                    banker_hand_json, self.player_points, self.banker_points,
                    self.strategy_note, self.main_choice
                ))
            
            # 获取ID
            result = cursor.fetchone()
            if result:
                self.id = result[0]
            
            conn.commit()
            return True
        
        except Exception as e:
            print(f"保存模拟轮次错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def get_by_simulation(sim_id, limit=100):
        """获取某个模拟的所有轮次"""
        conn = get_db_connection()
        if not conn:
            return []
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('''
                SELECT * FROM simulation_rounds 
                WHERE simulation_id = %s 
                ORDER BY round_id ASC
                LIMIT %s
            ''', (sim_id, limit))
            
            data = cursor.fetchall()
            return [SimulationRound.from_dict(row) for row in data]
        
        except Exception as e:
            print(f"获取模拟轮次错误: {str(e)}")
            return []
        
        finally:
            if cursor:
                cursor.close()
            conn.close()


class Deck:
    """牌组记录模型类，对应decks表"""
    
    def __init__(self, id=None, timestamp=None, simulation_id=None, deck_data=None, original_size=0, deck_seed=None):
        """初始化牌组记录对象"""
        self.id = id
        self.timestamp = timestamp or get_timestamp()
        self.simulation_id = simulation_id
        self.deck_data = deck_data or []
        self.original_size = original_size or len(self.deck_data)
        self.deck_seed = deck_seed
    
    @staticmethod
    def from_dict(data):
        """从字典创建对象"""
        instance = Deck()
        for key, value in data.items():
            if key == 'deck_data' and isinstance(value, str):
                setattr(instance, key, json.loads(value))
            else:
                setattr(instance, key, value)
        return instance
    
    def to_dict(self):
        """将对象转换为字典"""
        result = {
            'id': self.id,
            'timestamp': self.timestamp,
            'simulation_id': self.simulation_id,
            'deck_data': self.deck_data,
            'original_size': self.original_size,
            'deck_seed': self.deck_seed
        }
        return result
    
    def save(self):
        """保存到数据库"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            cursor = conn.cursor()
            
            # 牌组数据转JSON
            deck_data_json = json.dumps(self.deck_data)
            
            if self.id:  # 更新
                cursor.execute('''
                    UPDATE decks SET
                    timestamp = %s, simulation_id = %s, deck_data = %s, 
                    original_size = %s, deck_seed = %s
                    WHERE id = %s
                    RETURNING id
                ''', (
                    self.timestamp, self.simulation_id, 
                    deck_data_json, self.original_size, self.deck_seed,
                    self.id
                ))
            else:  # 插入
                cursor.execute('''
                    INSERT INTO decks (
                        timestamp, simulation_id, deck_data, original_size, deck_seed
                    ) VALUES (%s, %s, %s, %s, %s)
                    RETURNING id
                ''', (
                    self.timestamp, self.simulation_id, 
                    deck_data_json, self.original_size, self.deck_seed
                ))
            
            # 获取ID
            result = cursor.fetchone()
            if result:
                self.id = result[0]
            
            conn.commit()
            return True
        
        except Exception as e:
            print(f"保存牌组记录错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def get_by_simulation(sim_id):
        """获取某个模拟的牌组"""
        conn = get_db_connection()
        if not conn:
            return None
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM decks WHERE simulation_id = %s', (sim_id,))
            data = cursor.fetchone()
            
            if not data:
                return None
            
            return Deck.from_dict(data)
        
        except Exception as e:
            print(f"获取牌组记录错误: {str(e)}")
            return None
        
        finally:
            if cursor:
                cursor.close()
            conn.close()


class BetStrategyTable:
    """下注策略表模型类，对应bet_strategy_tables表"""
    
    def __init__(self, id=None, name="", description="", created_at=None, 
                 updated_at=None, is_default=False, strategy_content=""):
        """初始化下注策略表对象"""
        self.id = id
        self.name = name
        self.description = description
        self.created_at = created_at or get_timestamp()
        self.updated_at = updated_at or get_timestamp()
        self.is_default = is_default
        self.strategy_content = strategy_content  # 原始策略文本内容
    
    @staticmethod
    def from_dict(data):
        """从字典创建对象"""
        instance = BetStrategyTable()
        for key, value in data.items():
            setattr(instance, key, value)
        return instance
    
    def to_dict(self):
        """将对象转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'table_data': self.get_table_data(),  # 通过解析策略内容生成
            'created_at': self.created_at,
            'updated_at': self.updated_at,
            'is_default': self.is_default,
            'strategy_content': self.strategy_content
        }
        return result
    
    @staticmethod
    def parse_strategy_text(strategy_text):
        """
        将策略文本解析为策略表数据
        
        格式示例:
        +1000:1000        -> 如果上局赢了1000，本局下注1000
        -2000:3000        -> 如果上局输了2000，本局下注3000
        +2000,+2000,+2000:1000  -> 如果连续三局赢了2000，本局下注1000
        +2000/+3000/+4000:1000  -> 如果上局赢了2000或3000或4000，本局下注1000
        
        Args:
            strategy_text: 策略文本内容
            
        Returns:
            解析后的策略表数据，格式为 [{条件列表: 下注金额}, {条件列表: 下注金额}, ...]
        """
        table_data = []
        
        # 按行分割策略文本，从前端textbox输入的换行符有可能是\r\n或\n，需要统一处理
        lines = strategy_text.strip().replace('\r', '').split('\n')
        
        for line in lines:
            # 跳过空行和注释行
            line = line.strip()
            if not line or line.startswith('#'):
                continue
                
            # 尝试解析策略规则
            try:
                # 分离条件和下注金额
                if ':' in line:
                    condition_part, bet_amount_str = line.split(':', 1)
                    
                    # 解析下注金额
                    bet_amount = int(bet_amount_str.strip())
                    
                    # 解析条件
                    condition_part = condition_part.strip()
                    
                    # 添加到策略表{condition_part: bet_amount}
                    table_data.append({condition_part: bet_amount})
            except Exception as e:
                print(f"解析策略规则错误: {line} - {str(e)}")
                continue
        
        return table_data
    
    def get_table_data(self):
        """解析strategy_content并返回table_data"""
        if self.strategy_content:
            return self.parse_strategy_text(self.strategy_content)
        return []
    
    def save(self):
        """保存到数据库"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            cursor = conn.cursor()
            
            # 如果设为默认策略，先将其他所有策略设为非默认
            if self.is_default:
                cursor.execute("UPDATE bet_strategy_tables SET is_default = FALSE")
            
            if self.id:  # 更新
                self.updated_at = get_timestamp()
                cursor.execute('''
                    UPDATE bet_strategy_tables SET
                    name = %s, description = %s, strategy_content = %s,
                    updated_at = %s, is_default = %s
                    WHERE id = %s
                    RETURNING id
                ''', (
                    self.name, self.description, self.strategy_content,
                    self.updated_at, self.is_default, self.id
                ))
            else:  # 插入
                cursor.execute('''
                    INSERT INTO bet_strategy_tables (
                        name, description, strategy_content, created_at, updated_at, is_default
                    ) VALUES (%s, %s, %s, %s, %s, %s)
                    RETURNING id
                ''', (
                    self.name, self.description, self.strategy_content,
                    self.created_at, self.updated_at, self.is_default
                ))
            
            # 获取ID
            result = cursor.fetchone()
            if result:
                self.id = result[0]
            
            conn.commit()
            return True
        
        except Exception as e:
            print(f"保存下注策略表错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            conn.close()
    
    @staticmethod
    def get_by_id(strategy_id):
        """根据ID获取对象"""
        conn = get_db_connection()
        if not conn:
            return None
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM bet_strategy_tables WHERE id = %s', (strategy_id,))
            data = cursor.fetchone()
            
            if not data:
                return None
            
            return BetStrategyTable.from_dict(data)
        
        except Exception as e:
            print(f"获取下注策略表错误: {str(e)}")
            return None
        
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close()
    
    @staticmethod
    def get_by_name(name):
        """根据名称获取对象"""
        conn = get_db_connection()
        if not conn:
            return None
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM bet_strategy_tables WHERE name = %s', (name,))
            data = cursor.fetchone()
            
            if not data:
                return None
            
            return BetStrategyTable.from_dict(data)
        
        except Exception as e:
            print(f"获取下注策略表错误: {str(e)}")
            return None
        
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close()
    
    @staticmethod
    def get_default():
        """获取默认策略表"""
        conn = get_db_connection()
        if not conn:
            return None
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM bet_strategy_tables WHERE is_default = TRUE')
            data = cursor.fetchone()
            
            if not data:
                # 如果没有默认策略，尝试获取任意一个策略
                cursor.execute('SELECT * FROM bet_strategy_tables LIMIT 1')
                data = cursor.fetchone()
                
                if not data:
                    # 如果仍然没有，返回None
                    return None
            
            return BetStrategyTable.from_dict(data)
        
        except Exception as e:
            print(f"获取默认下注策略表错误: {str(e)}")
            return None
        
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close()
    
    @staticmethod
    def get_all():
        """获取所有策略表"""
        conn = get_db_connection()
        if not conn:
            return []
        
        cursor = None
        try:
            cursor = conn.cursor(cursor_factory=RealDictCursor)
            cursor.execute('SELECT * FROM bet_strategy_tables ORDER BY id ASC')
            data = cursor.fetchall()
            
            return [BetStrategyTable.from_dict(row) for row in data]
        
        except Exception as e:
            print(f"获取下注策略表列表错误: {str(e)}")
            return []
        
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close()
    
    @staticmethod
    def delete(strategy_id):
        """删除策略表"""
        conn = get_db_connection()
        if not conn:
            return False
        
        cursor = None
        try:
            # 检查是否为默认策略
            cursor = conn.cursor()
            cursor.execute("SELECT is_default FROM bet_strategy_tables WHERE id = %s", (strategy_id,))
            result = cursor.fetchone()
            
            if not result:
                return False
            
            is_default = result[0]
            
            if is_default:
                # 不允许删除默认策略
                return False
            
            # 执行删除
            cursor.execute('DELETE FROM bet_strategy_tables WHERE id = %s', (strategy_id,))
            conn.commit()
            return True
        
        except Exception as e:
            print(f"删除下注策略表错误: {str(e)}")
            conn.rollback()
            return False
        
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close() 